package cn.ly.design.structure;

import java.util.ArrayList;
import java.util.List;

/**
 * 组合模式
 * 使用场景：将多个对象组合在一起进行操作，常用于表示树形结构中，例如二叉树
 * @author liuyu
 *
 */
public class Composite {
	public static void main(String[] args) {
		Tree tree = new Tree("root");
		
		TreeNode c1 = new TreeNode("c1");
		
		TreeNode c2 = new TreeNode("c2");
		TreeNode c2c1 = new TreeNode("c2c1");
		TreeNode c2c2 = new TreeNode("c2c2");
		c2.add(c2c1);
		c2.add(c2c2);
		
		tree.getRoot().add(c1);
		tree.getRoot().add(c2);
		
		
		
		
	}
}

class TreeNode{
	private String value;
	private TreeNode parent;
	private List<TreeNode> children = new ArrayList<TreeNode>();
	
	public TreeNode(String value){
		this.value = value;
	}
	
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	public TreeNode getParent() {
		return parent;
	}
	public void setParent(TreeNode parent) {
		this.parent = parent;
	}
	
	//增加子节点
	public void add(TreeNode node){
		children.add(node);
	}
	
	//删除子节点
	public void remove(TreeNode node){
		children.remove(node);
	}
	
	//获得所有子节点
	public List<TreeNode> getChildren(){
		return this.children;
	}
	
}

class Tree{
	private TreeNode root;
	
	public Tree(String value){
		this.root = new TreeNode(value);
	}

	public TreeNode getRoot() {
		return root;
	}
}